//
//  AllOrderVc.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//

import UIKit
import XLPagerTabStrip
import MJRefresh
import UtilCore
import RxSwift
import RickonCore
import EmptyDataView
import BrandonCore


class AllOrderVc: Empty_TVc,CombinedOrderProtocol {
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var Custom_TableView: UITableView!
    
    @IBOutlet weak var tableView_Top: NSLayoutConstraint!
    
    @IBOutlet weak var tableView_Bottom: NSLayoutConstraint!
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    let header = MJRefreshNormalHeader()            //顶部刷新
    
    let footer = MJRefreshAutoNormalFooter()        //底部刷新
    
    var orderListVm:GetOrderListVm?                 //获取订单列表
    
    var dataArr:[TheOrderListModel]?{
        didSet{
            self.Custom_TableView.reloadData()      //获取数据源同时刷新列表
        }
    }
    
    var cancelVm:CancelOrderVm?                     //取消订单
    
    var deleteVm:DeleteOrderVm?                     //删除订单
    
    var ConfirmVm:ConfirmOrderVm?                   //确认收货
    
    var index = -1                                  //判断所属哪个ViewController
    

    /****************************Storyboard 绑定方法区域****************************/
    @IBAction func ChangeOrderStatus(_ sender: UIButton) {
        let model = dataArr![sender.tag]
        if sender.titleLabel?.text == "取消订单"{
            if model.payarray.count > 1{
                
                self.combinedOrderEvent(vc: self, type: "qx", model: model.payarray, payid: model.payid)
                
            }else{
                
                self.showAlert((UtilCore.alertmsg[100052004]?.msgtitle)!, title: (UtilCore.alertmsg[100052001]?.msgtitle)!, handler: { _ in
                
                    self.cancelVm?.cancelOrder.onNext(model.payid)
                
                })
                
            }
        }
        if sender.titleLabel?.text == "立即付款"{
            
             if model.payarray.count > 1{
                self.combinedOrderEvent(vc: self, type: "fk", model: model.payarray, payid: model.payid)
            }else{
                _ = "pay".openURL(["orderid":"","ordersumamount":(Double(model.orderamount) - model.paycoupon).getPriceStr(),"payid":model.payid,"ordertype":"OS"])
            }
        }
        if sender.titleLabel?.text == "删除订单"{
            
            self.showAlert((UtilCore.alertmsg[100052002]?.msgtitle)!, title: (UtilCore.alertmsg[100052001]?.msgtitle)!, handler: { _ in
            
                self.deleteVm?.deleteOrder.onNext(self.dataArr![sender.tag].orderid)
            
            })
        
        }
        if sender.titleLabel?.text == "评价"{
            
            _ = "evaluation".openURL(["orderid":model.orderid])
        }
        if sender.titleLabel?.text == "确认收货"{
            
            self.showAlert((UtilCore.alertmsg[100052005]?.msgtitle) ?? "", title: (UtilCore.alertmsg[100052001]?.msgtitle) ?? "", handler: { _ in
            
                self.ConfirmVm?.confirmOrderId.onNext(model.orderid)
                
            })
        
        }
        if sender.titleLabel?.text == "查看物流"{
            _ = "logistics".openURL(["orderid":model.orderid])
        }
    }
    /**
     显示提示框
     */
    func showAlert(_ message:String ,title:String ,handler: ((UIAlertAction) -> Void)?) {
        let aleatView = UIAlertController(title:title , message: message, preferredStyle:.alert)
        let archiveAction = UIAlertAction.init(title: "确定", style: .default, handler: handler)
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
        aleatView.addAction(cancelAction)
        aleatView.addAction(archiveAction)
        self.present(aleatView, animated: true, completion: nil)
    }
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let _ = AppData.loginedUser{
            if case AppDataState.audited = AppData.appState{
                if isrefresh_orderList != false{
                    
                    if index == 0{
                        self.getListRequest(evaluate: "", status: "")
                    }else if index == 1{
                        self.getListRequest(evaluate: "", status: "0")
                    }else if index == 2{
                        self.getListRequest(evaluate: "", status: "1,2")
                    }else if index == 3{
                        self.getListRequest(evaluate: "", status: "3,4")
                    }else if index == 4{
                        self.getListRequest(evaluate: "0", status: "5,6")
                    }
                    self.Custom_TableView.contentOffset = CGPoint(x: 0, y: 0)
                    isrefresh_orderList = false
                }
                
            }else{
                AuditInfoView.showByView(supView: self.Custom_TableView)
                self.Custom_TableView.isScrollEnabled = false
            }
            
        }else{
            AuditInfoView.showByView(supView: self.Custom_TableView)
            self.Custom_TableView.isScrollEnabled = false
        }
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if index == 0{
            self.getListRequest(evaluate: "", status: "")
        }else if index == 1{
            self.getListRequest(evaluate: "", status: "0")
        }else if index == 2{
            self.getListRequest(evaluate: "", status: "1,2")
        }else if index == 3{
            self.getListRequest(evaluate: "", status: "3,4")
        }else if index == 4{
            self.getListRequest(evaluate: "0", status: "5,6")
        }
        NotificationCenter.default.addObserver(self, selector: #selector(refreshing(_:)), name: .WXPaysuccess, object: nil)
    }
    func refreshing(_ notification: NSNotification) {
        self.header.beginRefreshing()
    }

    override func setupUI() {
        //添加空数据代理(品牌)
        self.Custom_TableView.dzn_tv_emptyDelegate = self
        self.Custom_TableView.dzn_tv_emptyDataSource = self
        self.Custom_TableView.delegate = self
        self.Custom_TableView.dataSource = self
        self.Custom_TableView.tableFooterView = UIView()
        
        // 上拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(AllOrderVc.headerRefresh))
        self.Custom_TableView.mj_header = header
        
        // 下拉加载更多
        footer.setRefreshingTarget(self, refreshingAction: #selector(AllOrderVc.footerRefresh))
        footer.isAutomaticallyHidden = true
        self.Custom_TableView.mj_footer = footer
    }
    
    
    func getListRequest(evaluate:String,status:String){
        
        self.orderListVm?.evaluate = evaluate
        self.orderListVm?.orderStatus.value = status
        self.orderListVm?.orderStat = status
    }
    
    
    override func bindToViewModel(){
        
        self.orderListVm = GetOrderListVm(
            input:(
                refreshTriger: rx.sentMessage(#selector(AllOrderVc.headerRefresh)).map { _ in () },
                loadMoreTriger: rx.sentMessage(#selector(AllOrderVc.footerRefresh)).map { _ in () }
            )
        )
        
        self.orderListVm?.backDate
            .asObservable()
            .do(onNext:{ [unowned self] _ in
                self.errorPageView.isHidden = true
            })
            .skip(1)
            .subscribe(onNext:{ data in
                
                self.showEmptyView = true
                self.dataArr = data
                
            }).addDisposableTo(disposeBag)
        
        
//        self.orderListVm.
        
        
        //显示加载动画
        self.orderListVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        //绑定错误
        self.orderListVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        //-----
        //错误处理
        self.orderListVm?
            .refresherror
            .asObserver()
            .bindTo(self.rx_showerrorpage)
            .addDisposableTo(disposeBag)
        
        self.errorPageView
            .reloadSubject
            .bindTo(self.orderListVm!.reloadTrigger)
            .addDisposableTo(disposeBag)
        
        self.orderListVm?
            .error
            .bindTo(self.view.rx_error)
            .addDisposableTo(disposeBag)
        
        
        //判断是否还有数据如果有就继续加载,没有则提示已经展示全部

        self.orderListVm?
            .hasNextPage.asDriver()
            .asObservable()
            .subscribe(onNext:{ hasNextPage in
            if !hasNextPage{
                self.footer.endRefreshingWithNoMoreData()
            }else{
                self.footer.resetNoMoreData()
            }
        }).addDisposableTo(disposeBag)
        
        
        //----------
        //取消订单
        self.cancelVm = CancelOrderVm()
        
        cancelVm?.backDate.asObservable().subscribe(onNext:{ data in
            
            if data == true{
                
                isrefresh_orderList = true
                if self.index == 0{
                    self.orderListVm?.orderStatus.value = ""
                    self.orderListVm?.orderStat = ""
                }else{
                    self.orderListVm?.orderStatus.value = "0"
                    self.orderListVm?.orderStat = "0"
                }
            }
            
        }).addDisposableTo(disposeBag)
        
        cancelVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //----------
        //删除订单
        self.deleteVm = DeleteOrderVm()
        
        deleteVm?.backDate.asObservable().subscribe(onNext:{ data in
            
            if data == true{
                isrefresh_orderList = true
                if self.index == 0{
                    self.orderListVm?.orderStatus.value = ""
                    self.orderListVm?.orderStat = ""
                }else{
                    self.orderListVm?.orderStatus.value = "\(self.index)"
                    self.orderListVm?.orderStat = "\(self.index)"
                }
            }
            
        }).addDisposableTo(disposeBag)
        
        self.deleteVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        //----------
        //确认收货
        self.ConfirmVm = ConfirmOrderVm()
        
        self.ConfirmVm?.backDate.asObserver().subscribe(onNext:{ result in
            if result == true{
                isrefresh_orderList = true
                if self.index == 0{
                    self.orderListVm?.orderStatus.value = ""
                    self.orderListVm?.orderStat = ""
                }else{
                    self.orderListVm?.orderStatus.value = "3,4"
                    self.orderListVm?.orderStat = "3,4"
                }
            }
            
        }).addDisposableTo(disposeBag)
        
        self.ConfirmVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        
    }
    
    func footerRefresh(){
        self.footer.endRefreshing()
    }
    func headerRefresh(){
        self.header.endRefreshing()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    
//    func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
//        if index == 0{
//            return IndicatorInfo(title: "全部")
//        }else{
//            
//            return IndicatorInfo(title: ["全部","待付款","待发货","待收货","待评价"][self.index!])
//        }
//        
//    }

}
extension AllOrderVc:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if let data = dataArr{
            return data.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArr![section].array.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        /*
         *  订单商品信息()
         */
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! OrderTableViewCell
        
        cell.item = dataArr![indexPath.section].array[indexPath.row]
        guard #available(iOS 9.0, *) else {
            cell.setNeedsUpdateConstraints()
            cell.updateConstraintsIfNeeded()
            return cell
        }
        return cell
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        /*
         *  订单店铺信息.订单状态
         */
        let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! HeaderTableViewCell
        cell.item = dataArr![section]
        
        guard #available(iOS 9.0, *) else {
            cell.setNeedsUpdateConstraints()
            cell.updateConstraintsIfNeeded()
            return cell
        }
        return cell.contentView
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "footer") as! FooterTableViewCell
        
        cell.item = dataArr![section]
        cell.left_Button.tag = section
        cell.right_Button.tag = section
        guard #available(iOS 9.0, *) else {
            cell.setNeedsUpdateConstraints()
            cell.updateConstraintsIfNeeded()
            return cell.contentView
        }
        return cell.contentView
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 47.5
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        if dataArr?[section].orderstatus == "2" || dataArr?[section].orderstatus == "1"{
            return 63.5
        }else{
            if #available(iOS 9.0, *){
                return 111
            }else{
                return 103
                
            }
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let str = dataArr?[indexPath.section].array[indexPath.row].orderid{

            isrefresh_orderList = false
            _ = "order_detail".openURL(["id":str])
        }
    }
}
extension AllOrderVc:EmptyDataSource{
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        return Theme.getEmptyDesc("您还没有相关订单~")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        return UIImage.init(named: "Listkong_Image", in: SansaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
    
}


